<template>
  <div>
    <div class="search">
      <Search :searchType="searchType" @getSearchData="getSearchData"></Search>
    </div>
    <div class="headeButton">
      <el-button type="primary" @click="addFn">添加内容</el-button>
    </div>
    <div class="draggable2" style="padding: 20px">
      <el-table row-key="id" :data="tableData" style="width: 100%">
        <template v-for="(item, index) in oldList" :key="`col_${index}`">
          <el-table-column
            v-if="item.type == 1"
            :prop="newList[index].prop"
            :label="item.label"
            align="center"
            show-overflow-tooltip
          >
          </el-table-column>
          <el-table-column
            v-else-if="item.type == 2"
            :prop="newList[index].prop"
            :label="item.label"
            align="center"
          >
            <template #default="scope">
              <el-button type="warning" size="small" @click="changeTableFn(scope.row)"
                >修改</el-button
              >
              <el-popconfirm title="是否确认删除" @confirm="confirmDeleteFn(scope.row)">
                <template #reference>
                  <el-button type="danger" size="small"> 删除 </el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
          <el-table-column
            v-else-if="item.type == 3"
            :prop="newList[index].prop"
            :label="item.label"
            align="center"
          >
            <template #default="scope">
              <el-image style="width: 80px; height: 80px" :src="scope.row[newList[index].prop]" />
            </template>
          </el-table-column>
          <el-table-column
            v-else-if="item.type == 4"
            :prop="newList[index].prop"
            :label="item.label"
            align="center"
          >
            <template #default="scope">
              <span v-if="scope.row[newList[index].prop] == 1">否</span>
              <span v-else>是</span>
            </template>
          </el-table-column>
        </template>
      </el-table>
      <el-pagination
        :current-page="pageData.page"
        :page-size="pageData.size"
        :page-sizes="[10, 20, 30, 40]"
        layout="total, sizes, prev, pager, next"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <el-dialog
      @close="closeFn"
      v-model="dialogVisibleAdd"
      width="500"
      :before-close="dialogBeforeCloseFn"
    >
      <div>
        <el-form
          ref="formAddRef"
          :rules="rules"
          :model="formAdd"
          label-width="auto"
          style="max-width: 800px"
        >
          <el-form-item label="图片">
            <el-upload
              :limit="1"
              :file-list="image"
              :action="baseURL2 + 'api/uploadAvatar'"
              list-type="picture-card"
              :on-success="handSuccessFnZh"
              :on-preview="handlePictureCardPreviewZh"
            >
              <el-icon><Plus /></el-icon>
            </el-upload>
          </el-form-item>
          <el-form-item label="门店名称：" prop="name">
            <el-input v-model="formAdd.name" class="imputeWidth" />
          </el-form-item>
          <el-form-item label="负责人：" prop="linkman">
            <el-input v-model="formAdd.linkman" class="imputeWidth" />
          </el-form-item>

          <el-form-item label="联系方式：" prop="phone">
            <el-input v-model="formAdd.phone" class="imputeWidth" />
          </el-form-item>
          <el-form-item label="门店账号：" prop="account">
            <el-input v-model="formAdd.account" class="imputeWidth" />
          </el-form-item>
          <el-form-item label="门店密码：" prop="password">
            <el-input v-model="formAdd.password" class="imputeWidth" />
          </el-form-item>
          <el-form-item label="门店国家：" prop="country">
            <el-select
              @change="selectCountryFn"
              v-model="formAdd.country"
              placeholder="Select"
              style="width: 240px"
            >
              <el-option
                v-for="(item, index) in countryEn"
                :key="index"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="门店区域：" prop="region">
            <el-cascader v-model="formAdd.region" :options="regionData" :props="props" />
          </el-form-item>
          <el-form-item label="合作方式：" prop="type">
            <el-select v-model="formAdd.type" placeholder="Select" style="width: 240px">
              <el-option
                v-for="(item, index) in agency"
                :key="index"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="是否可以跨区域发货：" prop="crossDomain">
            <el-select v-model="formAdd.crossDomain" placeholder="Select" style="width: 240px">
              <el-option label="否" value="1" />
              <el-option label="是" value="0" />
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer" style="display: flex; justify-content: center">
          <el-button type="primary" @click="confirmFn(0)"> 确定 </el-button>
          <el-button @click="confirmFn(1)">取消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog v-model="dialogVisibleImage">
      <div style="width: 100%; height: 100%">
        <img style="width: 100%; height: 100%" w-full :src="dialogImage" alt="Preview Image" />
      </div>
    </el-dialog>
  </div>
</template>
 
<script setup >
import { cityData, cityDataUS } from '@/components/js/addressOptions'
import { getstorelist2, registerStore, storeDelete, storeChange, storeAuditSerach } from '@/http/api/store.js'
import Sortable from 'sortablejs'
import { onMounted, reactive, ref, defineExpose } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { baseURL } from '@/http/request.js'
import { ElMessage } from 'element-plus'
import Search from '@/components/search/index.vue'
// 只适合做平级的table行和列拖动
let agency = [
  {
    value: '施工店',
    label: '施工店'
  },
  {
    value: '授权店',
    label: '授权店'
  },
  {
    value: '旗舰店',
    label: '旗舰店'
  },
  {
    value: '市级运营商',
    label: '市级运营商'
  },
  {
    value: '省级代理商',
    label: '省级代理商'
  }, {
    value: '国家级代理商',
    label: '国家级代理商'
  }
]
let countryEn = [
  { label: 'United States', value: 'US' },
  { label: 'China', value: 'CN' },
  { label: 'United Arab Emirates (Dubai)', value: 'AE' },
  { label: 'India', value: 'India' },
  { label: 'Malaysia', value: 'Malaysia' },
  { label: 'Netherlands', value: 'Netherlands' },
  { label: 'Peru', value: 'Peru' },
  { label: 'El Salvador', value: 'El Salvador' },
  { label: 'Saudi Arabia', value: 'Saudi Arabia' },
  { label: 'South Korea', value: 'South Korea' },
  { label: 'Thailand', value: 'Thailand' },
  { label: 'Vietnam', value: 'Vietnam' },
  { label: 'Russia', value: 'Russia' },
  { label: 'Mexico', value: 'Mexico' },
  { label: 'Egypt', value: 'Egypt' },
  { label: 'Amsterdam', value: 'Amsterdam' },
]
let baseURL2 = baseURL
const oldList = ref()
const newList = ref()
let searchType = ref([
  {
    title: '门店名称：',
    type: 1,
    model: 'name',
    hint: '请输入'
  }, {
    title: '负责人：',
    type: 1,
    model: 'linkman',
    hint: '请输入负责人'
  }, {
    title: '门店区域：',
    type: 1,
    model: 'region',
    hint: '请输入门店区域'
  }, {
    title: '联系方式：',
    type: 1,
    model: 'phone',
    hint: '请输入电话'
  }, {
    title: '门店账号：',
    type: 1,
    model: 'account',
    hint: '请输入门店账号'
  },
])
// 表头
const tableItems = ref([
  {
    label: '门店名称',
    prop: 'name',
    type: 1
  },
  {
    label: '负责人',
    prop: 'linkman',
    type: 1
  },
  {
    label: '联系方式',
    prop: 'phone',
    type: 1
  },
  {
    label: '门店账号',
    prop: 'account',
    type: 1
  },
  {
    label: '门店密码',
    prop: 'password',
    type: 1
  },
  {
    label: '门店区域',
    prop: 'region',
    type: 1
  },
  {
    label: '合作方式',
    prop: 'type',
    type: 1
  },
  {
    label: '是否可以跨区域发货',
    prop: 'crossDomain',
    type: 4
  },
  {
    label: '头像',
    prop: 'head',
    type: 3
  },
  {
    label: '操作',
    prop: 'age',
    type: 2
  },
])

// 表体数据
let tableData = ref([])
let formAdd = reactive({})
let image = ref([])
let dialogVisibleImage = ref(false)
let regionData = ref([])
let pageData = reactive({
  page: 1,
  size: 10,
  status: [1]
})
const selectCountryFn = (data) => {
  console.log(cityDataUS)
  console.log(data)
  if (data == 'US') {
    regionData.value = cityDataUS
    console.log(cityDataUS)
  } else {
    regionData.value = cityData
  }
  console.log(regionData.value)
}
const getData = async () => {
  let data = {
    ...pageData,
    ...serachData
  }
  const res = await storeAuditSerach(data)
  tableData.value = res.data.res
  total.value = res.data.total
}
let dialogVisibleAdd = ref(false)
let total = ref(0)
const addFn = () => {
  dialogVisibleAdd.value = true
}
const closeFn = () => {
  dialogVisibleAdd.value = false
}

const rules = reactive({
  name: [
    { required: true, message: '请输入', trigger: 'blur' },
  ],
  linkman: [
    { required: true, message: '请输入', trigger: 'blur' },
  ],
  phone: [
    { required: true, message: '请输入', trigger: 'blur' },
  ],
  account: [
    { required: true, message: '请输入', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入', trigger: 'blur' },
  ],
  image: [
    { required: true, message: '请上传图片', trigger: 'blur' },
  ],
  region: [
    { required: true, message: '请输入', trigger: 'blur' },
  ],
  type: [
    { required: true, message: '请输入', trigger: 'blur' },
  ], country: [
    { required: true, message: '请选择', trigger: 'blur' },
  ],
  crossDomain: [
    { required: true, message: '请输入', trigger: 'blur' },
  ]
})
let serachData = reactive({})
const getSearchData = async (data) => {
  Object.assign(serachData, data)
  getData()
}
// 上传成功
const handSuccessFnZh = (data) => {
  formAdd.head = data.image_url
}
let formAddRef = ref()
// 点击添加或这修改按钮
const confirmFn = async (number) => {
  if (number == 0) {
    await formAddRef.value.validate(async (valid, fields) => {
      if (valid) {
        try {
          if (!formAdd.id) {
            await registerStore(formAdd)
            ElMessage({
              message: '添加成功',
              type: 'success',
            })
          } else {
            delete formAdd.upDate
            delete formAdd.create_time
            await storeChange(formAdd)
            ElMessage({
              message: '修改成功',
              type: 'success',
            })
          }
          getData()
        } catch (error) {
          ElMessage({
            message: '失败',
            type: 'error',
          })
        }
      } else {
        console.log(111)
        console.log(fields)
        ElMessage({
          message: '请补充完整信息',
          type: 'error',
        })
      }
    })


  }

  formAdd = reactive({})

  dialogVisibleAdd.value = false
}
// 关闭弹窗
const dialogBeforeCloseFn = () => {
  formAdd.titleZh = ''
  formAdd.detilsZh = ''
  formAdd.titleEn = ''
  formAdd.detilsEn = ''
  formAdd.titleEn = ''
  image.value = []

  dialogVisibleAdd.value = false
}
// 修改size
const handleSizeChange = (data) => {
  pageData.size = data
  getData()
}
// 修改页数
const handleCurrentChange = (data) => {
  pageData.page = data
  getData()
}
// 确定删除
const confirmDeleteFn = async (data) => {
  try {
    const res = await storeDelete({ id: data.id })
    ElMessage({
      message: '删除成功',
      type: 'success',
    })
    getData()
  } catch (error) {
    ElMessage({
      message: '删除失败',
      type: 'error',
    })
  }

}
// 修改
const changeTableFn = (data) => {
  let upData = JSON.parse(JSON.stringify(data))
  dialogVisibleAdd.value = true
  upData.region = JSON.parse(upData.region)
  Object.assign(formAdd, upData)
  if (data.country == 'US') {
    regionData.value = cityDataUS
  } else {
    regionData.value = cityData
  }

  image.value = [{
    url: data.head,
    name: '11'
  }]
}
let dialogImage = ref('')
const handlePictureCardPreviewZh = (data) => {
  dialogVisibleImage.value = true
  dialogImage.value = data.url ? data.url : data.response.image_url
}
onMounted(() => {
  oldList.value = JSON.parse(JSON.stringify(tableItems.value))
  newList.value = JSON.parse(JSON.stringify(tableItems.value))
  getData()
})
defineExpose({ getData })
</script>
<style lang="scss" scoped>
.imputeWidth {
  width: 260px;
}
</style>